package com.yuyou.tas.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.tas.admin.service.IAuthOrganService;
import com.yuyou.tas.admin.vo.req.AuthOrgan;
import com.yuyou.tas.admin.vo.req.AuthOrganPerson;
import com.yuyou.tas.admin.vo.req.AuthOrganPersonUpdate;
import com.yuyou.tas.admin.vo.req.AuthOrganUpdate;
import com.yuyou.tas.service.api.admin.dto.DtoAuthOrgan;
import com.yuyou.tas.service.api.admin.dto.DtoAuthOrganDetail;
import com.yuyou.tas.service.api.admin.dto.SimpleSubSecReqVo;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.admin.AuthOrganizationEnums;
import com.yuyou.tas.util.exception.BusinessException;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(value="AuthOrganController",description="机构操作接口")
@Validated
@RestController
@RequestMapping(value="/api/authOrgan")
public class AuthOrganController  extends BaseController{

    @Autowired
    private IAuthOrganService autkOrganService;

    @ApiOperation(value="分页查询机构")
    @RequestMapping(value="/findAuthOrgan",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<DtoAuthOrgan> findAuthOrgan(@Validated @ModelAttribute PageParams pageParams,
                                                    @ApiParam(value = "机构名称")@RequestParam(value = "orgName", required = false) String orgName,
                                                    @ApiParam(value = "合作状态-0：试用期、1：合约期、2：终止")@RequestParam(value = "status", required = false) String status){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoAuthOrgan> queryPgn = new Pagination<>();
        if(!StringUtils.isEmpty(orgName)){
            conditions.put("orgName", orgName.trim());
        }
        if(!StringUtils.isEmpty(status)){
            conditions.put("status", status.trim());
        }
        conditions.put("type", AuthOrganizationEnums.type.institution.getValue());//机构类型
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = autkOrganService.findOrgPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<DtoAuthOrgan> list = autkOrganService.findOrgPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value="插入机构")
    @RequestMapping(value="/addAuthOrgan",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult addAuthOrgan(HttpServletRequest request , @Validated @ModelAttribute AuthOrgan authOrgan) throws Exception {
        if(authOrgan.getUserTimeStart().getTime() >= authOrgan.getUserTimeEnd().getTime()){
            return ReturnResult.returnRes(false,"开始时间必须小于结束时间",null);
        }
        List<SimpleSubSecReqVo> simpleSubSecReqVos = JSONObject.parseObject(authOrgan.getSubSec(), new TypeReference<List<SimpleSubSecReqVo>>(){});
        if(CollectionUtils.isEmpty(simpleSubSecReqVos)){
            throw new BusinessException("年级科目权限至少选择一个");
        }
        authOrgan.setSss(simpleSubSecReqVos);
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo res = autkOrganService.addAuthOrgan(authOrgan , user);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }

    @ApiOperation(value="更新机构")
    @RequestMapping(value="/updateAuthOrgan",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<String> updateAuthOrgan(@Validated @ModelAttribute AuthOrganUpdate authOrgan){
        if(authOrgan.getUserTimeStart().getTime() >= authOrgan.getUserTimeEnd().getTime()){
            return ReturnResult.returnRes(false,"开始时间必须小于结束时间",null);
        }
        List<SimpleSubSecReqVo> simpleSubSecReqVos = JSONObject.parseObject(authOrgan.getSubSec(), new TypeReference<List<SimpleSubSecReqVo>>(){});
        if(CollectionUtils.isEmpty(simpleSubSecReqVos)){
            throw new BusinessException("年级科目权限至少选择一个");
        }
        authOrgan.setSss(simpleSubSecReqVos);
        ResBoolSimpleInfo res = autkOrganService.updateAuthOrgan(authOrgan);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }

    @ApiOperation(value="删除机构")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "合作机构id", paramType="query", required = true)})
    @RequestMapping(value="/delAuthOrgan",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult delAuthOrgan(@NotNull(message="ID不能为空")Long id){
        ResBoolSimpleInfo res = autkOrganService.delAuthOrgan(id);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }

    @ApiOperation(value="分页查询合作个人")
    @RequestMapping(value="/findAuthOrganPerson",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<DtoAuthOrgan> findAuthOrganPerson(@Validated @ModelAttribute PageParams pageParams,
                                                          @ApiParam(value = "个人手机号码或名称")@RequestParam(value = "phoneOrName", required = false) String phoneOrName,
                                                          @ApiParam(value = "合作状态-0：试用期、1：合约期、2：终止")@RequestParam(value = "status", required = false) String status){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoAuthOrgan> queryPgn = new Pagination<>();
        if(!StringUtils.isEmpty(phoneOrName)){
            conditions.put("phoneOrName", phoneOrName.trim());
        }
        if(!StringUtils.isEmpty(status)){
            conditions.put("status", status.trim());
        }
        conditions.put("type", AuthOrganizationEnums.type.person.getValue());//机构类型
        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);
        int total = autkOrganService.findOrgPageCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<DtoAuthOrgan> list = autkOrganService.findOrgPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }

    @ApiOperation(value="插入个人合作")
    @RequestMapping(value="/addAuthOrganPerson",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult addAuthOrganPerson(HttpServletRequest request , @Validated @ModelAttribute AuthOrganPerson authOrganPerson) throws Exception {
        if(authOrganPerson.getUserTimeStart().getTime() >= authOrganPerson.getUserTimeEnd().getTime()){
            return ReturnResult.returnRes(false,"开始时间必须小于结束时间",null);
        }

        List<SimpleSubSecReqVo> simpleSubSecReqVos = JSONObject.parseObject(authOrganPerson.getSubSec(), new TypeReference<List<SimpleSubSecReqVo>>(){});
        if(CollectionUtils.isEmpty(simpleSubSecReqVos)){
            throw new BusinessException("年级科目权限至少选择一个");
        }
        authOrganPerson.setSss(simpleSubSecReqVos);
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo res = autkOrganService.addAuthOrganPerson(authOrganPerson , user);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }

    @ApiOperation(value="更新个人合作")
    @RequestMapping(value="/updateAuthOrganPerson",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult updateAuthOrganPerson( @Validated @ModelAttribute AuthOrganPersonUpdate authOrganPerson){
        if(authOrganPerson.getUserTimeStart().getTime() >= authOrganPerson.getUserTimeEnd().getTime()){
            return ReturnResult.returnRes(false,"开始时间必须小于结束时间",null);
        }
        List<SimpleSubSecReqVo> simpleSubSecReqVos = JSONObject.parseObject(authOrganPerson.getSubSec(), new TypeReference<List<SimpleSubSecReqVo>>(){});
        if(CollectionUtils.isEmpty(simpleSubSecReqVos)){
            throw new BusinessException("年级科目权限至少选择一个");
        }
        authOrganPerson.setSss(simpleSubSecReqVos);
        ResBoolSimpleInfo res = autkOrganService.updateAuthOrganPerson(authOrganPerson);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }

    @ApiOperation(value="删除合作个人")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "合作个人id", paramType="query", required = true)})
    @RequestMapping(value="/delAuthOrganPerson",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult delAuthOrganPerson(@NotNull(message="ID不能为空")Long id){
        ResBoolSimpleInfo res = autkOrganService.delAuthOrgan(id);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),null);
    }


    @ApiOperation(value="通过ID获取合作个人/机构详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "id", paramType="query", required = true)})
    @RequestMapping(value="/getAuthOrganDetail",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<DtoAuthOrganDetail> getAuthOrganDetail(@NotNull(message="ID不能为空")Long id){
        ResBoolSimpleInfo res = autkOrganService.getByID(id);
        return ReturnResult.returnRes(res.isSuccess(),res.getMessage(),res.getData());
    }

}
